import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
    selector: 'app-iframe-use',
    templateUrl: './iframe-use.component.html',
    styleUrls: ['./iframe-use.component.less'],
})
export class IframeUseComponent implements OnInit {
    iframeUrl: string = 'http://127.0.0.1:5500/src/app/other/iframe-use/iframe.html';
    time = '30';

    constructor(private sanitizer: DomSanitizer) {

    }

    ngOnInit(): void {
        // 监听iframe发来的消息
        window.addEventListener('message', (event) => {
            // 添加源检查以提高安全性
            // if (event.origin !== 'http://127.0.0.1:5500') return;

            if (event.data === 'iframeLoaded') {
                console.log('父页面监测到子页面iframe加载完成');
                // iframe加载完成后调用changeTime函数
                this.triggerCalculate(this.time);
            }
        });
    }

    // 调用iframe中的calculate方法
    triggerCalculate(number) {
        const iframe = document.querySelector('iframe');
        if (iframe && iframe.contentWindow) {
            console.log('父页面发送信息-iframe.contentWindow', iframe.contentWindow);
            // 使用postMessage发送消息
            iframe.contentWindow.postMessage({
                type: 'changeTime',
                value: number
            }, 'http://127.0.0.1:5500');
        }
    }

    clickFunction(event) {
        console.log('clickFunction', event);
        this.triggerCalculate(event);
    }
}
